import 'dart:async';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wch/constant/resource_constant.dart';
import 'package:wch/helper/event_manager.dart';
import 'package:wch/helper/user_wrap_helper.dart';
import 'package:wch/model/ble.dart';
import 'package:wch/page/set_wifi_pass.dart';
import 'package:wch/page/set_wifi_success.dart';
import 'package:wch/utils/navigator_utils.dart';
import 'package:wch/widget/common_widget.dart';
import 'package:wch/widget/padding_widget.dart';
import 'package:wch/widget/text_widget.dart';

import '../native/native.dart';
import '../utils/log_utils.dart';
import '../widget/alert_view.dart';

class StartSetWifiPage extends StatefulWidget {
  StartSetWifiPage({super.key, required this.bleModel, this.model});

  final BleModel bleModel;
  UserWrapModel? model;
  @override
  State<StartSetWifiPage> createState() => _StartSetWifiPageState();
}

class _StartSetWifiPageState extends State<StartSetWifiPage> implements EventManagerInterface {

  OverlayEntry? entry;
  String _getUserName(String? name) {
    if (name == null)  return '';
    if (name!.length > 4) {
      return '${name.substring(0, 3)}...';
    }
    return name;
  }
  @override
  Widget build(BuildContext context) {
    return CommonScaffold(
        title: '开始配网',
        body: Container(
          color: themeBGC,
          child: Container(
            margin: EdgeInsets.all(15.w),
            width: ScreenUtil().screenWidth - 30.w,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(7.5.w)),
              color: Colors.white,
            ),
            child: Column(
              children: [
                VerPadding(100.h),
                Image.asset(
                  aioIcon,
                  width: 80.w,
                  height: 80.w,
                ),
                VerPadding(30.h),
                Text(
                  '设备号：${widget.bleModel.deviceName}',
                  style: TextStyle(
                    fontSize: 16,
                    color: Color(0xFF3E3F42),
                    fontWeight: FontWeight.w500,
                  ),
                ),
                VerPadding(15.h),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    F13TitleText(_getUserName(widget.bleModel.userModel?.name), color: F2TextColor),
                    HorPadding(5.w),
                    Visibility(
                      visible: widget.bleModel.userModel?.sex != null,
                      child: Image.asset(
                        widget.bleModel.userModel?.sex == '男' ? patientMaleIcon : patientFemaleIcon,
                        width: 10.w,
                        height: 10.w,
                      ),
                    ),
                    HorPadding(10.w),
                    F13TitleText(widget.bleModel.userModel?.mobile ?? '', color: F2TextColor),

                  ],
                ),
                Expanded(child: Container()),
                Container(
                  margin: EdgeInsets.symmetric(horizontal: 30.w),
                  child: CommonBtn(
                    callback: () {
                      if (wifiName == 'empty') {
                        entry = OverlayEntry(builder: (ctx){
                          return CommonAlert(title: '配网提示', msg: '终端需要连接网络使用，请将手机连接Wi-Fi后进行一体机配网', callback: (id){}, entry: entry!, isSingleBtn:true, leftBtnText: '确定',);
                        });
                        Overlay.of(context).insert(entry!);
                        return;
                      }
                      NavigatorUtil.replace(context, SetPassPage(bleModel: widget.bleModel, model: widget.model,));
                    }, title: '开始配网',
                  ),
                ),
                VerPadding(50.h)
              ],
            ),
          ),
        ));
  }

  @override
  void initState() {
    EventManager.getIns().addObserver(this);
    if (Platform.isIOS) {
      NativeUtils.startIOSLocation();
    }
    wifiNameTimer = Timer.periodic(Duration(seconds: 1), (timer){
      NativeUtils.getWifiName();
    });
  }


  @override
  void dispose() {
    super.dispose();
    wifiNameTimer?.cancel();
    EventManager.getIns().removeObserver(this);
  }

  Timer? wifiNameTimer;
  String? wifiName;
  @override
  void notify(String methodName, Map<dynamic, dynamic> data) {
    // TODO: implement notify
    if (methodName == getEventWifi) {
      wifiName = data['wifiName'];
      LogUtils.log('wifiname=$wifiName');
    }
  }

}
